<?php

class ImageHandler
{

    private $fOriginalImage;
    private $fResizedImage;
    private $fOriginalWidth = 0, $fOriginalHeight = 0;

    public function __construct()
    {
        
    }

    /**
     * Load image from path
     * @param type $imagePath 
     */
    public function Load($imagePath)
    {
        if (!file_exists($imagePath))
        {
            echo 'Error: File ' . $imagePath . ' does not exist!';
            exit;
        }

        $this->fOriginalImage = @imagecreatefromjpeg($imagePath) or
                $this->fOriginalImage = @imagecreatefromgif($imagePath) or
                $this->fOriginalImage = @imagecreatefrompng($imagePath);
        $this->fResizedImage = $this->fOriginalImage;
    }

    /**
     * Resize an image
     * @param int $width is the required width in pixels
     * @param int $height is the required height in pixels
     */
    public function Resize($width=NULL, $height=NULL)
    {
        $newWidth = 0;
        $newHeight = 0;

        $this->fOriginalWidth = imagesx($this->fOriginalImage);
        $this->fOriginalHeight = imagesy($this->fOriginalImage);

        if ($width != NULL && $height != NULL)
        {
            $newWidth = $width;
            $newHeight = $height;
        }
        else if ($width != NULL && $height == NULL)
        {
            $newWidth = $width;
            $newHeight = ($this->fOriginalHeight / $this->fOriginalWidth) * $newWidth;
        }
        else if ($width == NULL && $height != NULL)
        {
            $newHeight = $height;
            $newWidth = ($this->fOriginalWidth / $this->fOriginalHeight) * $newHeight;
        }

        $this->fResizedImage = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($this->fResizedImage, $this->fOriginalImage, 0, 0, 0, 0, $newWidth, $newHeight, $this->fOriginalWidth, $this->fOriginalHeight);
    }

    public function Crop($width, $height)
    {
        $cropedImage = imagecreatetruecolor($width, $height);

        $this->fOriginalWidth = imagesx($this->fOriginalImage);
        $this->fOriginalHeight = imagesy($this->fOriginalImage);
    }

    /**
     * Save image.
     * @param type $path is the path to save the image. If the path is null the image is going to be displayed.
     */
    public function Save($path=NULL)
    {
        imagepng($this->fResizedImage, $path);
    }

}

?>
